# -*- coding: utf-8 -*-
from . import BaseController
from settings import logger
from backend.libs.args_util import *
from backend.models import Goods, GoodsPrice, GoodsPriceRelation, GoodsBanner, GoodsCategory, GoodsOrder
from backend.libs import myjson as json
from django.db import connection
from datetime import datetime


class GoodsListController(BaseController):

    def get(self):
        args = PageArgs(self, 'get', 'goodsName', 'state')
        gs = Goods.objects.filter(state=args.state)

        if args.goodsName:
            gs = gs.filter(name__contains=args.goodsName)

        paginator = self.pagination(gs.all(), number_per_page=args.pageSize)
        return self.render_json(data=paginator)

class BatchUpdateGoodsController(BaseController):

    def post(self):
        updated_goods = []
        data = json.loads(self.request.body)
        goods_ids = data.get('goodsIds', [])
        gs = Goods.objects
        # notice_video_ids = []
        if goods_ids:
            gs = gs.filter(id__in=goods_ids)

            for attr in ('state', 'site'):
                print(attr)
                if attr in data:
                    print(attr, data[attr])
                    gs.update(**{attr: data[attr], 'update_time': datetime.now()})

                for g in gs:
                    g.save()

            updated_goods = gs.filter(id__in=goods_ids)
        return self.render_json(data={'goods': [v.to_dict() for v in updated_goods]})


class DelGoodsBaseController(BaseController):

    def delete_goods(self, goods):
        if goods:
            # 删除商品分类关系
            GoodsPriceRelation.deleteGoods(goods);
            goods.banner.all().delete();
            cursor=connection.cursor()
            sql = 'delete from app_goods where id=%s' % goods.id
            print(sql)
            cursor.execute(sql)
        

class BatchDeleteController(DelGoodsBaseController):

    def post(self):
        data = json.loads(self.request.body)
        goods_ids = data.get('goodsIds', [])
        if not goods_ids:
            return self.render_json_code_999(msg='参数不能为空')
        goods_list = Goods.objects.filter(id__in=goods_ids).all()
        goods_orders = GoodsOrder.objects.filter(goods_id__in=goods_ids).all()
        if goods_orders:
            return self.render_json_code_999(msg='商品存在订单数据，无法删除！')
        for gs in goods_list:
            self.delete_goods(gs)

        return self.render_json(msg='删除成功')


class GoodsTypeListController(BaseController):

    def get(self):
        """商品价格列表
        """
        goods_price = GoodsPrice.objects.order_by('show_order')

        goods_type_name = self.get_argument('goodsTypeName', '')
        if goods_type_name:
            goods_price = goods_price.filter(name__contains=goods_type_name)

        state = self.int_argument('state', 0)
        goods_price = goods_price.filter(state=state).order_by('state', 'show_order')

        number_per_page = self.int_argument('pageSize', 100)
        paginator = self.pagination(goods_price.all(), number_per_page=number_per_page)
        return self.render_json(data=paginator) 


class AllGoodsCategoryController(BaseController):

    def get(self):
        """商品分类列表
        """
        print('**** ' * 10)
        goods_categories = GoodsCategory.objects.order_by('show_order').all()
        data = {
            'categories': [ c.to_dict() for c in goods_categories ]
        }
        return self.render_json(data=data) 


class CreateGoodsTypeController(BaseController):

    def post(self):
        """创建商品分类
        """
        data = json.loads(self.request.body)
        if not data['name']:
            return self.render_json(code=1001, msg='商品分类名称不能为空')
        goods_type_id = data['id']

        goods_type = GoodsPrice() if int(goods_type_id) <= 0 else GoodsPrice.objects.filter(id=goods_type_id).first()
        goods_type.name = data['name']
        price = int(data['price'])
        goods_type.price = price if price >= 0 else 0
        transaction_price = int(data['transaction_price'])
        goods_type.transaction_price = transaction_price if transaction_price >= 0 else 0
        goods_type.unit = data['unit']
        inventory = int(data['inventory'])
        goods_type.inventory = inventory if inventory >=0 else 0
        goods_type.state = data['state']
        goods_type.show_order = data['showOrder']
        goods_type.site = data['site']
        goods_type.save()
        return self.render_json(data=goods_type.to_dict())


class DelGoodsTypeController(BaseController):

    def post(self, goods_type_id):
        """删除商品分类
            删除商品分类需要先删除分类关联的商品
        """
        goods_type_id = int(goods_type_id)
        if goods_type_id > 0:
            goods_type = GoodsPrice.objects.filter(id=goods_type_id).first()
            if goods_type:
                # 删除商品分类关系
                GoodsPriceRelation.deleteGoodsPrice(goods_type);
                cursor=connection.cursor()
                sql = 'delete from app_goodsprice where id=%s' % goods_type_id
                cursor.execute(sql)
        return self.render_json()  


class GoodsPriceFormConfigController(BaseController):

    def get(self):
        """商品价格录入表格配置数据
        """
        goods_form1_config = {
            'inline': True, # 是否使用inline排版
            'labelPosition': 'right', # 标签对齐方式
            'labelWidth': '80px', # 标签宽度
            'size': 'small', # 尺寸
            'statusIcon': True, # 显示验证图标
            'formItemList': [
                {
                    "type": "input",
                    "label": "规格名称",
                    "disable": False,
                    "readonly": False,
                    "value": "",
                    "placeholder": "商品规格名称",
                    "rules": [
                        {
                            "required": True,
                            "message": "不能为空",
                            "trigger": "blur"
                        },
                        {
                            "min": 1,
                            "max": 8,
                            "type": "string",
                            "message": "长度在1~8个字符",
                            "trigger": "blur"
                        },
                        {
                            "pattern": "^[\\w\\u4e00-\\u9fa5-_]+$",
                            "message": "正则验证失败:^[\\w\\u4e00-\\u9fa5-_]+$",
                            "trigger": "blur"
                        }
                    ],
                    "key": "name",
                    "subtype": "text"
                },
                {
                    "type": "input",
                    "label": "计量单位",
                    "disable": False,
                    "readonly": False,
                    "value": "",
                    "placeholder": "商品计量单位",
                    "rules": [
                    ],
                    "key": "unit",
                    "subtype": "text"
                },
                {
                    "type": "number",
                    "label": "价格",
                    "value": 0,
                    "decimal1": 2,
                    "min": 0,
                    "max": 999998,
                    "prepend": "￥",
                    "append": "元",
                    "key": "price"
                },
                {
                    "type": "number",
                    "label": "优惠价格",
                    "value": 0,
                    "decimal1": 2,
                    "min": 0,
                    "max": 999998,
                    "prepend": "￥",
                    "append": "元",
                    "key": "transaction_price"
                },
                {
                    "type": "number",
                    "label": "库存数量",
                    "value": 1,
                    "decimal1": None,
                    "min": 0,
                    "max": 1000000,
                    "prepend": "",
                    "append": "",
                    "key": "inventory"
                }
            ]
        }
        data = {
            'goods_form1': goods_form1_config,
            'goods_form2': goods_form1_config,
            'goods_form3': goods_form1_config
        }
        return self.render_json(data=data)


class CreateGoodsController(BaseController):

    def post(self):
        """创建商品
        """
        data = json.loads(self.request.body)
        print(data)
        if not data['name']:
            return self.render_json(code=1001, msg='商品名称不能为空')
        goods_id = data['id']

        if int(goods_id) <= 0:
            print('here')
            goods = Goods()
        else:
            print('there')
            goods = Goods.objects.filter(id=goods_id).first()
            if not goods:
                return self.render_json(code=1001, msg='指定id的商品数据未找到')
            # 更新的话每次都重新创建关联关系
            GoodsPriceRelation.deleteGoods(goods);
            # banner关联都删除
            goods.banner.all().delete();

        goods.name = data['name']
        goods.image_file = data['image_file']
        goods.state = data['state']
        goods.show_order = data['showOrder']
        goods.category_id = data['category']
        sales = int(data['sales'])
        goods.sales = sales if sales >=0 else 0
        goods.detail = ','.join([ d['url'] for d in data['detail']])
        goods.site = data['site']
        goods.content = data['content']
        goods.tags = ','.join(data['tags'])
        goods.city = data['city']
        goods.save()

        # 创建视频banner
        banner_index = 1
        for banner in data['banner']:
            gb = GoodsBanner()
            gb.url = banner['url']
            gb.show_order = banner_index
            gb.state = 0
            gb.site = 0
            gb.save()
            # 商品添加与banner的关联
            goods.banner.add(gb)
            banner_index += 1

        # 保存商品与规格的关联关系
        goods_price_list = data['goodsPrice']
        tmp_index = 1
        for gp in goods_price_list:
            if gp['name']:
                tmp_goods_price = GoodsPrice()
                tmp_goods_price.name = gp['name']
                tmp_goods_price.price = int(gp['price'])
                tmp_goods_price.transaction_price = int(gp['transaction_price'])
                tmp_goods_price.unit = gp['unit']
                tmp_goods_price.inventory = int(gp['inventory'])
                tmp_goods_price.state = 0
                tmp_goods_price.site = 0
                tmp_goods_price.show_order = tmp_index
                tmp_goods_price.save()
                tmp_index += 1

                goods_price_relationship = GoodsPriceRelation.objects.create(goods=goods, goodsprice=tmp_goods_price)
                goods_price_relationship.save()

        return self.render_json(data=goods.to_dict())  
